package com.jxm.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.jxm.security.common.R;
import com.jxm.security.common.ResponseUtil;
import com.jxm.security.common.TokenUtils;
import com.jxm.security.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: jxm
 * @Description: JWT认证过滤器
 * @Date: 2022/5/24 22:48
 * @Version: 1.0
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(ObjectUtils.isEmpty(token)){ //为空
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userId = TokenUtils.getUserInfoFromToken(token);
        //从redis获取用户信息
        Object userInfo = redisTemplate.opsForValue().get("login" + userId);
        if(ObjectUtils.isEmpty(userInfo)){
//            ResponseUtil.out(response,R.error().message("用户未登录"));
            throw new RuntimeException("token过期期");
        }
        SysUser sysUser = JSONObject.parseObject(userInfo.toString(), SysUser.class);
        log.info("用户信息{}",sysUser);

        //存入到securityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(sysUser.getUser(),
                        null,sysUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);
//        SecurityContextHolder.clearContext();
    }
}
